package com.kotlin.demo

import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.util.concurrent.CancellationException

class Test04Launch {
    fun launchTest() {
        runBlocking {
            val job = launch {
                repeat(3) {
                    delay(100)
                    println("launchA $it")
                }
            }
            val job2 = async {
                repeat(3) {
                    delay(100)
                    println("launchB $it")
                }
            }
            println("1. launchJob.isActive：${job.isActive}")
            println("1. launchJob.isCancelled：${job.isCancelled}")
            println("1. launchJob.isCompleted：${job.isCompleted}")
            println("1. asyncJob.isActive：${job2.isActive}")
            println("1. asyncJob.isCancelled：${job2.isCancelled}")
            println("1. asyncJob.isCompleted：${job2.isCompleted}")

            job.start()
            job2.start()
            println("2. launchJob.isActive：${job.isActive}")
            println("2. launchJob.isCancelled：${job.isCancelled}")
            println("2. launchJob.isCompleted：${job.isCompleted}")
            println("2. asyncJob.isActive：${job2.isActive}")
            println("2. asyncJob.isCancelled：${job2.isCancelled}")
            println("2. asyncJob.isCompleted：${job2.isCompleted}")

            //休眠四百毫秒后再主动取消协程
            Thread.sleep(400)
            job.cancel(CancellationException("test"))
            job2.cancel(CancellationException("test"))

            //休眠四百毫秒防止JVM过快停止导致 invokeOnCompletion 来不及回调
            Thread.sleep(400)

            println("3. launchJob.isActive：${job.isActive}")
            println("3. launchJob.isCancelled：${job.isCancelled}")
            println("3. launchJob.isCompleted：${job.isCompleted}")
            println("3. asyncJob.isActive：${job2.isActive}")
            println("3. asyncJob.isCancelled：${job2.isCancelled}")
            println("3. asyncJob.isCompleted：${job2.isCompleted}")
        }


    }
}